const app = getApp();
const utils = require('../../utils/util.js');

Page({
  data: {
    full_loading: true,

    stag_wait: 5000,  // 关卡保留的毫秒数

    question_list: [],
    status: 0,  // 0.第一次进入小程序 1.关卡开始 2.答题 3.关卡结束 4.回看 5.闯关结束 6.简介页面（后来加的所以放这里了）
    g_index: 0,  // 答到第几关
    q_index: 0,  // 答到第几小题
    r_index: 0,  // 回看模式index
    answer_list: [],

    stage_cn: '',
    vh_arr: [],
    count_question: 0,
    count_success: 0,

    score: 0,  // 分数

    share_show: false,
    share_image: '',

    avatarUrl: '',
    nickName: '',
    remark_list: [],
    remark: '',

    auth: false  // 用户是否授权
  },
  onLoad() {
    this.questionList();
    this.remark();
  },
  // 初始化答题
  questionList() {
    app.ajax('api/questionList', null, res => {
      let question_list_str = wx.getStorageSync('question_list_str') || '';
      let status = wx.getStorageSync('status') || 0;
      let g_index = wx.getStorageSync('g_index') || 0;
      let q_index = wx.getStorageSync('q_index') || 0;
      let r_index = wx.getStorageSync('r_index') || 0;
      let answer_list = wx.getStorageSync('answer_list') || [];

      // 题目没有变化
      if (question_list_str === JSON.stringify(res)) {
        this.setData({
          status: status,
          g_index: g_index,
          q_index: q_index,
          r_index: r_index,
          answer_list: answer_list,
          question_list: res,
          stage_cn: utils.number_to_cn(g_index + 1)
        });
      } else {
        // 题目变化
        if (g_index === 0 && q_index === 0) {
          // 题目变化但还未开始答题
          this.setData({
            status: status,
            g_index: g_index,
            q_index: q_index,
            r_index: r_index,
            answer_list: answer_list,
            question_list: res,
            stage_cn: utils.number_to_cn(this.data.g_index + 1)
          }, () => {
            wx.setStorageSync('question_list_str', JSON.stringify(res));
          });
        } else {
          app.modal('题目库更新，请重新开始答题', () => {
            wx.setStorageSync('status', 1);
            wx.setStorageSync('g_index', 0);
            wx.setStorageSync('q_index', 0);
            wx.setStorageSync('r_index', 0);
            wx.setStorageSync('answer_list', []);
            wx.setStorageSync('question_list_str', JSON.stringify(res));

            this.setData({
              first: 1,
              question_list: res
            })
          });
        }
      }

      this.setData({ full_loading: false });

      if (status === 0) {
        setTimeout(() => {
          this.setData({ status: 6 });
          wx.setStorageSync('status', 6);
        }, this.data.stag_wait);
      } else if (status === 1) {
        wx.setStorageSync('status', 1);
        setTimeout(() => {
          this.setData({ status: 2 });
          wx.setStorageSync('status', 2);
        }, this.data.stag_wait);
      } else if (status === 5) {
        let count_some = this.count_some();
        this.setData({
          count_question: count_some.count_question,
          count_success: count_some.count_success,
          score: count_some.score
        }, () => {
          this.get_user_info();
        });
      }
    });
  },
  // 开始答题
  start() {
    this.setData({
      status: 1,
      stage_cn: utils.number_to_cn(this.data.g_index + 1)
    }, () => {
      wx.setStorageSync('status', 1);
      setTimeout(() => {
        this.setData({ status: 2 });
        wx.setStorageSync('status', 2);
      }, this.data.stag_wait);
    });
  },
  // 答题
  answer(e) {
    let g_index = this.data.g_index;
    let q_index = this.data.q_index;
    this.setData({ [`answer_list[${g_index}][${q_index}]`]: e.detail.value }, () => {
      wx.setStorageSync('answer_list', this.data.answer_list);
    });
  },
  // 上一题
  prev() {
    this.setData({ q_index: this.data.q_index - 1 }, () => {
      wx.setStorageSync('q_index', this.data.q_index);
    });
  },
  // 下一题
  next() {
    let data = this.data;
    let g_index = data.g_index;
    let q_index = data.q_index;
    let question_list = data.question_list;

    if (q_index < question_list[g_index].list.length - 1) {
      this.setData({ q_index: q_index + 1 }, () => {
        wx.setStorageSync('q_index', this.data.q_index);
      });
    } else {
      let vh_len = question_list[g_index].list.length % 5;
      let vh_arr = [];
      for (let i = 0; i < vh_len; i++) {
        vh_arr.push(null);
      }

      this.setData({
        q_index: 0,
        status: 3,
        vh_arr: vh_arr
      }, () => {
        wx.setStorageSync('q_index', 0);
        wx.setStorageSync('status', 3);
      })
    }
  },
  // 回看
  review(e) {
    this.setData({
      status: 4,
      r_index: e.currentTarget.dataset.index
    }, () => {
      wx.setStorageSync('status', 4);
      wx.setStorageSync('r_index', e.currentTarget.dataset.index);
    })
  },
  // 回看上一题
  review_prev() {
    this.setData({ r_index: this.data.r_index - 1 }, () => {
      wx.setStorageSync('r_index', this.data.r_index);
    });
  },
  // 回看下一题
  review_next() {
    this.setData({ r_index: this.data.r_index + 1 }, () => {
      wx.setStorageSync('r_index', this.data.r_index);
    });
  },
  // 下一关
  next_stage() {
    if (this.data.g_index < this.data.question_list.length - 1) {
      // 进入下一关
      this.setData({
        status: 1,
        g_index: this.data.g_index + 1,
        q_index: 0,
        r_index: 0,
        stage_cn: utils.number_to_cn(this.data.g_index + 2)
      }, () => {
        wx.setStorageSync('status', 1);
        wx.setStorageSync('g_index', this.data.g_index);
        wx.setStorageSync('q_index', this.data.q_index);
        wx.setStorageSync('r_index', this.data.r_index);

        setTimeout(() => {
          this.setData({ status: 2 });
          wx.setStorageSync('status', 2);
        }, this.data.stag_wait);
      })
    } else {
      // 闯关结束
      let count_some = this.count_some();
      this.setData({
        status: 5,
        count_question: count_some.count_question,
        count_success: count_some.count_success,
        score: count_some.score
      }, () => {
        wx.setStorageSync('status', this.data.status);
        this.get_user_info();
      })
    }
  },
  // 授权并查看成绩
  next_stage_auth(e) {
    if (e.detail.userInfo) {
      wx.showLoading({ mask: true });

      app.userAuth(res => {
        if (res) {
          wx.hideLoading();
          this.next_stage();
        } else {
          app.toast('授权失败，请重新授权');
        }
      });
    }
  },
  // 计算总题数和答对题数
  count_some() {
    let count_question = 0;
    let count_success = 0;
    let score = 0;

    for (let i = 0; i < this.data.question_list.length; i++) {
      for (let j = 0; j < this.data.question_list[i].list.length; j++) {
        count_question++;
        if (this.data.answer_list[i][j] === this.data.question_list[i].list[j].key) {
          count_success++;
        }
      }
    }

    score = Math.round(count_success / count_question * 100);

    return {
      count_question,
      count_success,
      score
    };
  },
  // 再次闯关
  again() {
    wx.showModal({
      title: '提示',
      content: '成绩将重新计算，确认重新闯关？',
      success: res => {
        if (res.confirm) {
          this.again_nei();
        }
      }
    });
  },
  // 重新答题
  again2() {
    wx.showModal({
      title: '提示',
      content: '确认重新答题吗？',
      success: res => {
        if (res.confirm) {
          this.again_nei();
        }
      }
    });
  },
  again_nei() {
    this.setData({
      status: 0,
      g_index: 0,
      q_index: 0,
      r_index: 0,
      answer_list: [],
      stage_cn: utils.number_to_cn(1)
    }, () => {
      wx.setStorageSync('status', this.data.status);
      wx.setStorageSync('g_index', this.data.g_index);
      wx.setStorageSync('q_index', this.data.q_index);
      wx.setStorageSync('r_index', this.data.r_index);
      wx.setStorageSync('answer_list', []);

      setTimeout(() => {
        this.setData({ status: 6 });
        wx.setStorageSync('status', 6);
      }, this.data.stag_wait);
    });
  },
  // 分享
  onShareAppMessage() {
    wx.showShareMenu();

    return {
      title: '三农理论知识测一测',
      imageUrl: '/images/share-img.jpg'
    };
  },
  // 打开山海文化官微
  openShanHaiWenHua() {
    wx.navigateToMiniProgram({
      appId: 'wx50f030c7f4a897ff',
      success(res) {
        console.log('成功', res);
      },
      fail(err) {
        console.log('失败', err);
      }
    })
  },
  create_image() {
    let promise1 = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: this.data.avatarUrl,
        success: function (res) {
          resolve(res);
        },
        fail() {
          wx.hideLoading();
          app.toast('生成失败，请重试');
        }
      })
    });

    let promise2 = new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: 'https://mp.wcip.net/res/dati/ec5c832c46abadbadbd4ec82444bec0.jpg',
        success(res) {
          resolve(res);
        },
        fail() {
          wx.hideLoading();
          app.toast('生成失败，请重试');
        }
      })
    });

    Promise.all([
      promise1, promise2
    ]).then(res => {
      var canvas = wx.createCanvasContext('share-canvas');

      // 绘制背景
      canvas.setFillStyle('#ffe3c3');
      canvas.rect(0, 0, 750, 163);
      canvas.fill();
      canvas.draw();

      canvas.setFillStyle('#fff0df');
      canvas.rect(0, 130, 750, 987);
      canvas.fill();
      canvas.draw(true);

      // 绘制头像
      canvas.save();
      canvas.beginPath();
      canvas.arc(144.5, 132, 94, 0, 2 * Math.PI);
      canvas.clip();
      canvas.drawImage(res[0].path, 50.5, 38, 188, 188);
      canvas.restore();
      canvas.draw(true);

      // 绘制分数
      canvas.setFontSize(120);
      canvas.setFillStyle("#ff4141");
      canvas.setTextAlign('center');
      canvas.fillText(this.data.score, 600, 150, 200);
      canvas.draw(true);

      // 绘制分数下面的线
      canvas.drawImage('/images/score-plat.png', 500, 180, 203, 46);
      canvas.draw(true);

      // 绘制评语
      canvas.setFontSize(32);
      canvas.setFillStyle("#666666");
      canvas.setTextAlign('center');

      let str = this.data.nickName + this.data.remark;
      let str_index = 0;
      let step = 20;
      let rest = str.substr(str_index, step);
      let str_count = 0;
      while (rest) {
        canvas.fillText(rest, 375, 350 + str_count * 50, 900);

        str_index += step;
        rest = str.substr(str_index, step);
        str_count++;
      }

      canvas.draw(true);

      // 绘制二维码
      let qrcode = res[1].path;
      canvas.drawImage(qrcode, 225, 580, 300, 300);
      canvas.draw(true);

      // 扫码文字
      canvas.setFontSize(35);
      canvas.setFillStyle("#666");
      canvas.setStrokeStyle("#666");
      canvas.setTextAlign('center');
      canvas.fillText('分享二维码，邀请好友参与答题', 375, 1000, 900);
      canvas.draw(true);

      setTimeout(() => {
        wx.canvasToTempFilePath({
          x: 0,
          y: 0,
          width: 750,
          height: 1150,
          destWidth: 750,
          destHeight: 1150,
          canvasId: 'share-canvas',
          success: res => {
            this.setData({
              share_image: res.tempFilePath,
              share_show: true
            });
            wx.hideLoading()
          },
          fail(res) {
            // 生成失败
          }
        })
      }, 500)
    });
  },
  // 获取用户信息（头像、昵称）
  get_user_info() {
    wx.getUserInfo({
      success: user => {
        let remark;
        if (this.data.score < 60) {
          remark = this.data.remark_list[0].remark;
        } else if (this.data.score < 80) {
          remark = this.data.remark_list[1].remark;
        } else if (this.data.score < 90) {
          remark = this.data.remark_list[2].remark;
        } else {
          remark = this.data.remark_list[3].remark;
        }

        this.setData({
          avatarUrl: user.userInfo.avatarUrl,
          nickName: user.userInfo.nickName,
          remark
        });
      }
    });
  },
  // 获取评语
  remark() {
    app.ajax('api/remark', null, res => {
      this.setData({ remark_list: res });
    });
  },
  save_album() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.writePhotosAlbum']) {
          wx.saveImageToPhotosAlbum({
            filePath: that.data.share_image,
            success() {
              app.modal('图片成功保存到相册了，快去分享朋友圈吧', () => {
                that.setData({ share_show: false });
              });
            },
            fail(err) {
              if (err.errMsg.indexOf('cancel') !== -1) {
                app.toast('保存已取消');
              } else {
                app.toast('保存失败');
              }
            }
          })
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              that.save_album();
            },
            fail() {
              that.setData({
                show_set_btn: true
              });
            }
          });
        }
      }
    });
  },
  // 打开设置
  hide_set_btn() {
    this.setData({ show_set_btn: false })
  }
});
